import { delDict, getDictList } from "@/api/modules/system/dict";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { showTips, confirm } from "@/utils/util";
import { getCurrentInstance, defineComponent, ComponentInternalInstance } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ElMessage } from "element-plus";
import DataDialog from "./components/dataDialog";
import { getPageSize } from "@/hooks/useTable";
export default defineComponent({
	props: {
		dictType: {
			type: Object,
			default() {
				return {};
			}
		},
		systemId: {
			type: String,
			default() {
				return "";
			}
		}
	},
	emits: [],
	setup(props) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
		const proTableRef = ref();

		const initParam = reactive({ dictName: "", pageSize: getPageSize({ offsetHeight: -76 }) });
		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		const getTableList = async (params: any) => {
			if (!props.dictType.dictType) {
				return { result: { records: [] } };
			}
			return getDictList({ ...params, dictType: props.dictType.dictType, systemId: props.systemId });
		};
		const btnList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			btnList.value = [
				{
					menuName: proxy?.$t("dict_datalist.btn.add"),
					path: "add",
					btnClass: "primary"
				},
				{
					menuName: proxy?.$t("dict_datalist.btn.del"),
					path: "del"
				}
			];
		});
		const currentItem = ref();
		const clickBtn = async (val: string, scope: any) => {
			switch (val) {
				case "add":
					detailDialog.visible = true;
					detailDialog.title = proxy?.$t("dict_datalist.dialog_title.add");
					currentItem.value = {
						status: 1,
						dictType: props.dictType.dictType,
						dictTypeName: props.dictType.dictName,
						systemId: props.systemId
					};
					break;
				case "del":
					if (scope.selectList.length == 0) return ElMessage.error("至少选择一条数据操作");
					confirm({ content: "是否删除当前选择的记录？" }).then(async flag => {
						if (!flag) {
							return;
						}
						let { code, message } = await delDict({ ids: scope.selectList.map((item: any) => item.dictCode) });
						let ok = showTips(code, "删除字典类型", message);
						if (ok) {
							proTableRef.value.getTableList();
						}
					});
					break;
				case "mod":
					detailDialog.visible = true;
					detailDialog.title = proxy?.$t("dict_datalist.dialog_title.modify");
					currentItem.value = { ...scope, dictTypeName: props.dictType.dictName };
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "dictLabel", label: proxy?.$t("dict_datalist.tablist_label.dictlabel") },
			{ prop: "dictValue", label: proxy?.$t("dict_datalist.tablist_label.dictvalue") },
			// { prop: "dictValue", label: "字段标识" },
			{ prop: "status", label: proxy?.$t("dict_datalist.tablist_label.status"), width: 100 },
			{ prop: "remark", label: proxy?.$t("dict_datalist.tablist_label.remark") },
			{ prop: "operation", label: proxy?.$t("dict_datalist.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const detailDialog = reactive({ visible: false, title: proxy?.$t("dict_datalist.dialog_title.add") });
		const state = reactive({
			searchParam: {} as any
		});
		watch(
			() => props.dictType.dictType,
			() => {
				proTableRef.value.reset();
			}
		);
		return () => {
			return (
				<div>
					<DataDialog
						width="600"
						v-model:visible={detailDialog.visible}
						title={detailDialog.title}
						detail={currentItem.value}
						onSubmit={() => {
							detailDialog.visible = false;
							proTableRef.value.getTableList();
						}}
					></DataDialog>
					<div class="mr-2">
						<ProTable
							ref={proTableRef}
							title={btnList.value.length ? "" : proxy?.$t("dict_datalist.tab_title.operation")}
							columns={columns}
							requestApi={getTableList}
							dataCallback={dataCallback}
							initParam={state.searchParam}
							selectId="dictCode"
							toolButton={false}
							custSearch
						>
							{{
								headerRightExt: () => {
									return (
										<div class="flex" style="height: 32px;">
											<el-input
												v-model={initParam.dictName}
												style="width:250px"
												placeholder={proxy?.$t("dict_datalist.input.placeholder")}
											/>
											<el-button onClick={() => proTableRef.value.getTableList()}>
												{proxy?.$t("dict_datalist.btn.query")}
											</el-button>
										</div>
									);
								},
								tableHeader: (scope: any) => {
									return btnList.value?.map((item: any) => {
										return (
											<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
												<i class={`iconfont ${item.icon}`}></i>
												{item.menuName}
											</el-button>
										);
									});
								},
								dictValue: (scope: any) => {
									try {
										return JSON.parse(scope.row.dictValue).value;
									} catch (error) {
										return scope.row.dictValue;
									}
								},
								dictName: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => clickBtn("mod", scope.row)}>
											{scope.row.dictName}
										</el-link>
									);
								},
								status: (scope: any) => {
									return (
										<OnlineStatus
											v-model={scope.row.status}
											onlineLabel={proxy?.$t("dict_datalist.status.online")}
											offlineLabel={proxy?.$t("dict_datalist.status.offline")}
										/>
									);
								},
								operation: (scope: any) => {
									return (
										<>
											<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("mod", scope.row)}>
												{proxy?.$t("dict_datalist.link.detail")}
											</el-link>
										</>
									);
								}
							}}
						</ProTable>
					</div>
				</div>
			);
		};
	}
});
